/*
 * Summary
 * Simple class that sends data(commands) to the server in a seperate AsyncTask thread
 */
package com.example.bluetoothexample.BluetoothLayer;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.bluetooth.BluetoothSocket;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

public class SendData{
	/*
	 * For debugging purposes
	 */
    private static final String TAG = "[SendData]";
    private static final boolean D = true;
	private String message;
	private static Handler handler;
	private static Controller controller;
	
	/*
	 * When the SendData class is instantiated it starts the AsyncTask thread with a provided message to send
	 * @param a BluetoothSocket that is connected, and a message the be sent
	 */
	public SendData(String message, Handler handler)
	{	
		controller = Controller.getInstance(handler);
		//this.bluetoothSocket = bluetoothSocket;
		this.message = message;
		new SendTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, controller.getBluetoothSocket());
	}
	/*
	 * The AsyncTask thread that sends a message via a connected sockets outputstream
	 * AsyncTask<doInBackgroundInputType,ProgressUpdateType,OutputType>
	 */
	 private class SendTask extends AsyncTask<BluetoothSocket, Integer, String> {
	     protected String doInBackground(BluetoothSocket... socket) {
	    	 Log.d(TAG, "message to be sent: " + message);
	    	 Log.e(TAG,""+socket[0].isConnected());
	    	 	
		 		DataOutputStream os;
		 		if(controller.checkBluetoothSupport())
		 		{
				try {
					os = new DataOutputStream(socket[0].getOutputStream());
					Log.e(TAG,""+socket[0].isConnected());
					os.write(message.getBytes());
					Log.e(TAG,"SendDataMethod");
					os.flush();
					
				} catch (IOException e) {
					Log.d(TAG,"SendDataMethod");
					e.printStackTrace();
					
				}
		 		}else{
		 			Log.d(TAG, "No BluetoothSupport");
		 		}
	         return "Done";
	     }

	     protected void onProgressUpdate(Integer... progress) {
	     }

	     protected void onPostExecute(String result) {
	     }
	 }
	
	
	
}
